<template>
  <div class="container">
    <TManageSidebar />
    <div class="right-content">
      <main class="main">
        <div class="statistics">
          <div class="statistic-item">
            <span>总课程节数: {{ totalClasses }}</span>
          </div>
          <div class="statistic-item">
            <span>总出勤率: {{ overallAverageRate }}%</span>
          </div>
        </div>
        <div class="charts">
          <div class="chart-container">
            <h2>课程出勤率统计</h2>
            <v-chart :option="attendanceChartOption" autoresize />
          </div>
        </div>
      </main>
    </div>
  </div>
</template>

<script setup>
import TManageSidebar from '@/components/TManageSidebar.vue';
import { ref, onMounted, computed } from 'vue';
import VChart from 'vue-echarts';
import { use } from 'echarts/core';
import { LineChart } from 'echarts/charts';
import {
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
} from 'echarts/components';
import { CanvasRenderer } from 'echarts/renderers';
import { getSignStatistics } from '@/api/sign'; // 修改为新的接口
import {useCourseManageIdStore} from '@/stores/courseManageId'; 

// 注册必须的组件
use([
  CanvasRenderer,
  LineChart,
  TitleComponent,
  TooltipComponent,
  GridComponent,
  LegendComponent,
  DataZoomComponent
]);

// 响应式数据
const classData = ref([]);
const totalClasses = ref(0);
const overallAverageRate = ref(0);
const courseManageIdStore = useCourseManageIdStore();

// 处理后端数据格式
const processAttendanceData = (data) => {
  const lectures = [];
  const attendanceRates = [];
  const absentRates = [];

  // 遍历排序后的课程数据
  Object.entries(data.classIdToAverageRateMap).forEach(([classId, rateStr], index) => {
    lectures.push(`第${index + 1}节课`);
    const rate = parseFloat(rateStr) / 100; // 转换为小数
    attendanceRates.push(rate);
    absentRates.push(1 - rate); // 计算缺勤率
  });

  return {
    lectures,
    attendanceRates,
    absentRates,
    total: data.totalClasses,
    overall: data.overallAverageRate
  };
};

// 图表配置生成器（优化版）
const createChartOption = (title, data) => {
  const showSlider = data.length > 5;
  
  return {
    title: {
      text: title,
      left: 'center',
      top: 0
    },
    tooltip: {
      trigger: 'axis',
      formatter: function (params) {
        let result = params[0].axisValueLabel + '<br/>';
        params.forEach(param => {
          result += `${param.seriesName}: ${(param.value * 100).toFixed(1)}%<br/>`;
        });
        return result;
      }
    },
    legend: {
      data: ['出勤率', '缺勤率'],
      top: 30
    },
    grid: {
      top: 80,
      left: 50,
      right: 50,
      bottom: showSlider ? 80 : 50,
      containLabel: true
    },
    dataZoom: [{
      type: 'slider',
      show: showSlider,
      xAxisIndex: 0,
      start: 0,
      end: showSlider ? Math.min(50, (5 / data.length) * 100) : 100,
      bottom: 20,
      height: 30,
      borderColor: 'transparent',
      backgroundColor: '#f5f7fa',
      fillerColor: 'rgba(64, 158, 255, 0.2)',
      handleStyle: {
        color: '#409EFF'
      },
      showDetail: true,
      moveOnMouseMove: false,
      minSpan: (1 / data.length) * 100,
      maxSpan: 100
    }],
    xAxis: {
      type: 'category',
      data: data.lectures,
      axisLabel: {
        rotate: 45,
        interval: 0,
        margin: 8
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: {
      type: 'value',
      min: 0,
      max: 1,
      interval: 0.2,
      axisLabel: {
        formatter: (value) => `${(value * 100).toFixed(0)}%`
      }
    },
    series: [
      {
        name: '出勤率',
        type: 'line',
        data: data.attendanceRates,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: { 
          width: 2,
          color: '#67C23A'  // 绿色表示出勤
        }
      },
      {
        name: '缺勤率',
        type: 'line',
        data: data.absentRates,
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        lineStyle: {
          width: 2,
          color: '#F56C6C'  // 红色表示缺勤
        }
      }
    ]
  };
};

// 计算属性
const attendanceChartOption = computed(() => {
  if (!classData.value.lectures) return {};
  return createChartOption('课程出勤率趋势', classData.value);
});

// 获取数据
const fetchData = async () => {
  try {
      const courseManageId = courseManageIdStore.courseManageId;
      console.log('查看courseManagId获取：',courseManageId);
      const res = await getSignStatistics(courseManageId);
      console.log('res',res);
      const processedData = processAttendanceData(res);
      classData.value = processedData;
      totalClasses.value = processedData.total;
      overallAverageRate.value = processedData.overall;
  } catch (error) {
    console.error('获取出勤数据失败:', error);
  }
};

// 初始化获取数据
onMounted(() => {
  if (courseManageIdStore.courseManageId) {
    fetchData();
  }
});
</script>

<style scoped>
.container {
  display: flex;
  min-height: 100vh;
}

.right-content {
  margin-left: 160px;
  flex: 1;
}

.statistics {
  margin: 20px;
  padding: 20px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  display: flex;
  justify-content: space-around;
}

.chart-container {
  height: 500px;  /* 适当增加高度 */
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
  padding: 20px;
  margin: 20px;
}

:deep(.echarts) {
  width: 100% !important;
  height: 100% !important;
}
</style>